package com.ycy.chuwenuniapp.utils;

import cn.hutool.core.codec.Base64;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ycy.chuwenuniapp.common.ResCodeEnum;
import com.ycy.chuwenuniapp.exception.CustomException;


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

public class ImageUtils {
    public static String imageBytesToBase64(byte[] imageBytes) {
        return Base64.encode(imageBytes);
    }

    public static String createQrCode(String url, Integer width, Integer height, InputStream extraImage) {
        if(width == null || height == null) throw new CustomException(ResCodeEnum.SERVER_ERROR,"生成二维码的宽度高度不能为空");
        HashMap<EncodeHintType, Object> qrCodeParamsMap = new HashMap<>();
        qrCodeParamsMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);  //二维码精度(纠错程度)
        qrCodeParamsMap.put(EncodeHintType.CHARACTER_SET,"utf-8");  //字符编码
        qrCodeParamsMap.put(EncodeHintType.MARGIN,1);  //二维码边距

        try {
            //将url写进二维码中，生成一个BitMatrix对象。该对象中存储的是以像素为单位的x,y轴的二维码点的坐标。
            BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height,qrCodeParamsMap);
            // int width2 = bitMatrix.getWidth();  //等同于生成BitMatrix对象时传入的width,height
            // int height2 = bitMatrix.getHeight();
            BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < width; y++) {
                    bufferedImage.setRGB(x,y,bitMatrix.get(x,y) ? 0xFF000000 : 0xFFFFFFFF);
                }
            }
            if(extraImage == null) return imageToBase64(bufferedImage);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String imageToBase64(BufferedImage bufferedImage) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage,"png",byteArrayOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException(ResCodeEnum.SERVER_ERROR,"图片转base64错误");
        }
        return Base64.encode(byteArrayOutputStream.toByteArray());
    }


}
